package online_store.model.bus;

import java.util.ArrayList;
import java.util.List;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import online_store.entity.ProductEntity;
import online_store.model.dao.ProductDao;
import online_store.model.dto.ProductDTO;

@Service
public class ProductBus {

	@Autowired
	private ProductDao productDao;
	
	@Autowired
	private CategoryBus categoryBus;
	
	/*
	 * -1: Duplicated name
	 */
	@Transactional(value="jpaTransactionManager")
	public int createProduct(ProductDTO dto){
		//validate duplicated user
		ProductDTO existedProduct = findByName(dto.getName());
		if(existedProduct != null){
			return -1;
		}
		
		//create
		productDao.createProduct(convertDto2En(dto));
		
		return 1;
	}
	
	@Transactional(value="jpaTransactionManager")
	public List<ProductDTO> findAll(){
		List<ProductDTO> dto_list = new ArrayList<>();
		List<ProductEntity> en_list = productDao.findAll();
		for(int i = 0; i < en_list.size(); i++){
			ProductDTO dto = convertEn2Dto(en_list.get(i));
			dto.setCategory_name(categoryBus.getCategory(dto.getCategory_id()).getName()); //get category name
			dto_list.add(dto);
		}
		return dto_list;
	}
	
	@Transactional(value="jpaTransactionManager")
	public ProductDTO getProduct(int productId){
		return convertEn2Dto(productDao.getProduct(productId));
	}
	
	@Transactional(value="jpaTransactionManager")
	public ProductDTO findByName(String name){
		return convertEn2Dto(productDao.findByName(name));
	}
	
	@Transactional(value="jpaTransactionManager")
	public int updateProduct(ProductDTO dto){
		//validate duplicated user
		ProductDTO existedProduct = findByName(dto.getName());
		if(existedProduct != null && !existedProduct.getName().equals(dto.getName())){
			return -1;
		}
		
		//create
		productDao.updateProduct(convertDto2En(dto));
		
		return 1;
	}
	
	@Transactional(value="jpaTransactionManager")
	public void deleteProduct(int productId){
		productDao.deleteProduct(productId);
	}
	
	
	private ProductEntity convertDto2En(ProductDTO dto){
		if(dto == null){
			return null;
		}
		ProductEntity en = new ProductEntity();
		en.setProduct_id(dto.getProduct_id());
		en.setName(dto.getName());
		en.setDesc(dto.getDesc());
		en.setImage(dto.getImage());
		en.setPrice(dto.getPrice());
		en.setCategory_id(dto.getCategory_id());
		en.setLast_update(dto.getLast_update());
		return en;
	}
	
	private ProductDTO convertEn2Dto(ProductEntity en){
		if(en == null){
			return null;
		}
		ProductDTO dto = new ProductDTO();
		dto.setProduct_id(en.getProduct_id());
		dto.setName(en.getName());
		dto.setDesc(en.getDesc());
		dto.setImage(en.getImage());
		dto.setPrice(en.getPrice());
		dto.setCategory_id(en.getCategory_id());
		dto.setLast_update(en.getLast_update());
		return dto;
	}
}
